﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity.Core.Objects;
using System.Linq;
using System.Text;
using SalesSys.Comm.DAL;

namespace SalesSys.DAL.Base
{

    public class EqlConditionAdapter : BaseSqlTextCondition<ObjectParameter>
    {
        public EqlConditionAdapter()
        {
            
        }
        protected override ObjectParameter CreateParameter(string fieldName, object value, int index)
        {
            var ic = value as IConvertible;
            Console.WriteLine(ic);
            string parameterName = string.Format("{0}{1}_{2}",  parameterKey, index, fieldName);
            return new ObjectParameter(parameterName,value) ;
        }
        protected override string GetFieldName(string fieldName)
        {
            return string.Format("it.[{0}]", fieldName);
        }
        /// <summary>
        /// 组合排序字段
        /// </summary>
        /// <param name="orderCols">列名，是否为降序，降序为true,升序为false</param>
        /// <returns></returns>
        public static string ToOrderBy(IEnumerable<KeyValuePair<string, ListSortDirection>> orderCols)
        {
            StringBuilder stb = new StringBuilder();
            string fmt = "it.{0} {1}";
            string aes = "";
            string desc = "desc";
            bool isFirst = true; 
            stb.Append(" ");
            foreach (var item in orderCols)
            {
                if (item.Key.ToCharArray().FirstOrDefault(p => !(char.IsLetterOrDigit(p) || p == '_')) != 0)
                    throw new ArgumentException("排序列名称必须为字母、数字或_");
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    stb.Append(",");
                }
                stb.AppendFormat(fmt, item.Key, item.Value == ListSortDirection.Descending ? desc : aes);
            }
            return stb.ToString();
        }

    }
}
